package nacos

import (
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/model"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/thinkeridea/go-extend/exunicode/exutf8"
	"github.com/zeromicro/go-zero/core/logx"
	tools "go-zero-project/common/utils"
	"go-zero-project/services/user/api/internal/config"
	"strings"
)

type TargetBO struct {
	ServiceName string
	Cluster     string
	Group       string
}

func NewTargetBO() *TargetBO {
	return &TargetBO{}
}

// BuilderTarget 转换URL
func (bo *TargetBO) BuilderTarget(target string) *TargetBO {
	inString, _ := exutf8.RuneIndexInString(target, strings.Index(target, "?"))
	tempStr := target[:inString]
	bo.ServiceName = tempStr[strings.LastIndex(tempStr, "/")+1:]
	paramSubStr := target[inString+1:]
	if len(paramSubStr) <= 0 {
		return bo
	}
	split := strings.Split(paramSubStr, "&")
	for _, v := range split {
		subSplitArr := strings.Split(v, "=")
		if subSplitArr[0] == "cluster" {
			bo.Cluster = subSplitArr[1]
		}
		if subSplitArr[0] == "group" {
			bo.Group = subSplitArr[1]
		}
	}
	return bo
}

// SelectOneHealthyInstance 获取监控实例
func (bo *TargetBO) SelectOneHealthyInstance(config *config.NacosConfig) (*model.Instance, error) {
	// 从缓存里面获取
	naocsConfig, clientConfig := InitNaocsConfig(config)
	client, newNamingErr := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: naocsConfig,
		},
	)
	if newNamingErr != nil {
		return nil, newNamingErr
	}
	param := vo.SelectOneHealthInstanceParam{
		Clusters:    []string{bo.Cluster},
		ServiceName: bo.ServiceName,
		GroupName:   bo.Group,
	}
	instances, err := client.SelectOneHealthyInstance(param)
	if err != nil {
		return nil, err
	}
	logx.Infof("SelectOneHealthyInstance,param:%s, result:%s", tools.BeanToJson(param), tools.BeanToJson(instances))
	return instances, nil
}
